package com.woniuxy.enjoylife.controller;


import com.woniuxy.enjoylife.entity.Role;
import com.woniuxy.enjoylife.entity.RecentComment;
import com.woniuxy.enjoylife.entity.Role;
import com.woniuxy.enjoylife.entity.Suggest;
import com.woniuxy.enjoylife.entity.User;
import com.woniuxy.enjoylife.entity.dto.*;
import com.woniuxy.enjoylife.enums.StateEnum;
import com.woniuxy.enjoylife.mapper.UserMapper;
import com.woniuxy.enjoylife.service.CommunityService;
import com.woniuxy.enjoylife.service.RecentCommentService;
import com.woniuxy.enjoylife.service.UserService;
import com.woniuxy.enjoylife.utils.PageResult;
import com.woniuxy.enjoylife.utils.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author teamEnjoyLife75
 * @since 2021-01-18
 */
@RestController
@RequestMapping("/user")
public class UserController {
    //打印信息工具
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;
    @Autowired
    CommunityService communityService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private HttpServletRequest request;
    @Resource
    private RecentCommentService recentCommentService;

    @RequestMapping("/findAll")
    @ResponseBody
    public List<User> findAll(){
        System.out.println(111);
        return userService.findAll();
    }

    /**
     * 自动登录
     * @return
     */
    @PostMapping("/logined")
    public ResponseResult logined(){
        ResponseResult<Object> responseResult = new ResponseResult<>();
        String token = request.getHeader("token");
        if(token != null && !token.equals("") && redisTemplate.opsForValue().get(token) != null && redisTemplate.opsForValue().get(token) != ""){
            responseResult.setState(StateEnum.SUCCESS);
        }else {
            responseResult.setState(StateEnum.ERROR);
        }
        return  responseResult;
    }

    /**
     * 登录请求
     * @param user
     * @param response
     * @return
     */
    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user,HttpServletResponse response){
//        if((Integer)request.getSession().getAttribute("id") == null){
//
//        }
        ResponseResult<Object> responseResult = new ResponseResult<>();
        //密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        User newUser = userService.findByAccountPwd(user.getAccount(),user.getPassword());
        if (newUser == null){
            responseResult.setStatusCode(501);
            responseResult.setState(StateEnum.ERROR);
            responseResult.setMessage("登录失败，请更改登录信息并稍后重试！");
        }else{
//            生成uuid放入redis中
            String uuid = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(uuid,newUser.getId());
            redisTemplate.expire(uuid,7, TimeUnit.DAYS);
//            返回数据并添加token请求头
            response.setHeader("token",uuid);
            response.setHeader("Access-Control-Expose-Headers","token");
            request.getSession().setAttribute("id",newUser.getId());


            //将用户角色放入请求头
//            List<Role> rolesList = userService.selectUserRole(newUser.getId());
//            String uuid2=UUID.randomUUID().toString();
//            redisTemplate.opsForValue().set(uuid2,rolesList.toString());
//            redisTemplate.expire(uuid2,7, TimeUnit.DAYS);
//            response.setHeader("role",rolesList.toString());
//            response.setHeader("Access-Control-Expose-Headers","role");


            responseResult.setStatusCode(200);
            responseResult.setState(StateEnum.SUCCESS);
        }
        return responseResult;
    }

    /**
     * 用户登出
     * @return
     */
    @PostMapping("/loguot")
    public void loguot(){
        String token = request.getHeader("token");
        //删除session记录
        request.getSession().removeAttribute("id");
        //删除redis记录
        redisTemplate.delete(token);
    }

    /**
     * 通过用户account，判断用户名是否存在
     */
    @RequestMapping("/findByAccount")
    public String findByAccount(String account){
        if(userService.findByAccount(account)){
            return "该用户名已存在！";
        }else {
            return "success";
        }
    }

    /**
     * 通过手机号，判断该手机号是否存在
     * @param user
     * @return
     */
    @PostMapping("findByEmail")
    public String findByEmail(@RequestBody User user){
        if(userService.findByEmail(user.getEmail())){
            return "该手机号已被注册，请更换邮箱！";
        }else {
            return "success";
        }
    }

    /**
     * 给邮箱发送验证码
     * @return
     */
    @RequestMapping("/sendCode")
    public ResponseResult sendCode(@RequestBody User user){
        String email = user.getEmail();
        ResponseResult<Object> responseResult = new ResponseResult<>();
        if(userService.sendCode(email,user.getStatus())){
            //发送成功
            responseResult.setStatusCode(200);
            responseResult.setMessage("success");
            responseResult.setState(StateEnum.SUCCESS);
        }else {
            //发送失败
            responseResult.setStatusCode(501);
            responseResult.setMessage("验证码发送失败!请检查邮箱，稍后重试！");
            responseResult.setState(StateEnum.ERROR);
        }
        return responseResult;
    }

    /**
     * 用户注册
     * @param
     * @return
     */
    @PostMapping("/register")
    public String register(@RequestBody RegisterDao registerDao){
        User user = new User();
        user.setAccount(registerDao.getAccount());
        user.setPassword(registerDao.getPassword());
        user.setEmail(registerDao.getEmail());
        if(userService.register(user,registerDao.getCode(),registerDao.getRole())){
            return "success";
        }else {
            return "注册失败，请重新填写信息，并重新发送验证码！";
        }
    }

    /**
     * 用户通过邮箱验证修改密码
     * @param registerDao
     * @return
     */
    @PostMapping("/updataByEmail")
    public ResponseResult updataByEmail(@RequestBody RegisterDao registerDao){
        ResponseResult<Object> responseResult = new ResponseResult<>();
        if (userService.updataByEmail(registerDao.getPassword(),registerDao.getCode(),registerDao.getEmail())){
            responseResult.setStatusCode(200);
            responseResult.setState(StateEnum.SUCCESS);
            responseResult.setMessage("修改密码成功！");
        }else{
            responseResult.setStatusCode(501);
            responseResult.setState(StateEnum.ERROR);
            responseResult.setMessage("修改失败！请输入正确的验证码并稍后重试！");
        }
        return responseResult;
    }


    /**
     * 用户修改密码
     * @param id
     * @param password
     * @return
     */
    @RequestMapping("/updatePwd")
    @ResponseBody
    public boolean updatePwd(int id,String password){
        return userService.updatePwd(id,password)>0?true:false;
    }

    /**
     * 用户修改密码
     * @param id
     * @param account
     * @return
     */
    @RequestMapping("/updateAccount")
    @ResponseBody
    public boolean updateAccount(int id,String account){return userService.updateAccount(id,account)>0?true:false;
    }

    /**
     * 用户修改头像
     * @param id
     * @param img
     * @return
     */
    @RequestMapping("/updateHead")
    @ResponseBody
    public boolean updateHead(int id,String img){
        return userService.updateHead(id,img)>0?true:false;
    };

    /**
     * 查询用户信息+房屋信息
     * @param
     * @return
     */
    @RequestMapping("/findDetail")
    @ResponseBody
    public UserDto findDetail(){
        int id = (int) request.getSession().getAttribute("id");
        UserDto userDto = userService.findDetail(id);
        return userDto;
    }



    /**
     * 用户投诉
     */
    @RequestMapping("/userSuggest")
    @ResponseBody
    public boolean userSuggest(Suggest suggest){
        return userService.userSuggest(suggest) > 0 ? true:false;
    }


    /**
     * 检查物业账户注册是否可用
     * @param account
     * @return
     */
    @RequestMapping("/checkVillage")
    public ResponseResult checkVillage(String account){
        ResponseResult<Object> responseResult = new ResponseResult<>();
        if(userService.checkVillage(account)){
            responseResult.setStatusCode(200);
            responseResult.setMessage("can village");
            responseResult.setState(StateEnum.SUCCESS);
        }else{
            responseResult.setStatusCode(500);
            responseResult.setMessage("not village");
            responseResult.setState(StateEnum.ERROR);
        }
        return responseResult;
    }

    /**
     * 平台物业用户注册
     * @param propertyDto
     * @return
     */
    @PostMapping("/registerProperty")
    public ResponseResult registerProperty(@RequestBody PropertyDto propertyDto){
        ResponseResult<Object> responseResult = new ResponseResult<>();
        //检查小区能否注册
        //检查物业用户能否注册
        if(communityService.haveCommunity(propertyDto.getCommunity()) && userService.checkVillage(propertyDto.getAccount())){
            //可以进行注册
            if(userService.registerProperty(propertyDto)){
                //注册成功
                responseResult.setStatusCode(200);
                responseResult.setState(StateEnum.SUCCESS);
                responseResult.setMessage("SUCCESS");
            }else{
                //注册失败
                responseResult.setStatusCode(501);
                responseResult.setState(StateEnum.ERROR);
                responseResult.setMessage("注册失败！请稍后重试！");
            }
        }else {
            //不可以进行注册
            responseResult.setStatusCode(502);
            responseResult.setState(StateEnum.ERROR);
            responseResult.setMessage("注册信息有误！注册失败！请重新填写注册信息！");
        }
        return responseResult;
    }

    /**
     * 平台用户管理信息
     * @param type 分类
     * @param size 每页条数
     * @param currentPage 当前页
     * @return
     */
    @RequestMapping("/usersInfo")
    public ResponseResult usersInfo(int type,int size,int currentPage){
        PageResult<UserInfoDto> pageResult = userService.usersInfo(type,size,currentPage);
        ResponseResult<PageResult<UserInfoDto>> responseResult = new ResponseResult<>();
        responseResult.setStatusCode(200);
        responseResult.setState(StateEnum.SUCCESS);
        responseResult.setData(pageResult);
        return responseResult;
    }

    /**
     * 平台用户状态切换
     * @param user
     * @return
     */
    @PostMapping("/userSwitch")
    public ResponseResult userSwitch(@RequestBody User user){
        ResponseResult<Object> responseResult = new ResponseResult<>();
        if(userService.userSwitch(user)){
            responseResult.setStatusCode(200);
            responseResult.setMessage("SUCCESS");
            responseResult.setState(StateEnum.SUCCESS);
        }else{
            responseResult.setStatusCode(500);
            responseResult.setMessage("服务器繁忙，请稍后重试！");
            responseResult.setState(StateEnum.ERROR);
        }
        return responseResult;
    }

    /**
     * 平台用户信息修改
     * @param userInfoDto
     * @return
     */
    @PostMapping("/userInfoChange")
    public ResponseResult userInfoChange(@RequestBody UserInfoDto userInfoDto){
        ResponseResult<Object> responseResult = new ResponseResult<>();
        if(userService.userInfoChange(userInfoDto)){
            responseResult.setStatusCode(200);
            responseResult.setState(StateEnum.SUCCESS);
            responseResult.setMessage("SUCCESS");
        }else{
            responseResult.setStatusCode(501);
            responseResult.setState(StateEnum.ERROR);
            responseResult.setMessage("修改信息错误，请重新修改并重试！");
        }
        return responseResult;
    }

    /**
     * 平台商家申请列表
     * @return
     */
    @RequestMapping("/findApply")
    public ResponseResult findApply(){
        ResponseResult<List<User>> responseResult = new ResponseResult<>();
        responseResult.setStatusCode(200);
        responseResult.setState(StateEnum.SUCCESS);
        responseResult.setData(userService.findApply());
        return responseResult;
    }

    /**
     * 查询用户头像和昵称
     * @return
     */
    @RequestMapping("/getdetail")
    @ResponseBody
    public ResponseResult getetail(){
        //用户id
        int id = (int) request.getSession().getAttribute("id");
        ResponseResult responseResult = new ResponseResult();
        HeadAccountDto headAccountDto = userService.getDetail(id);
        if(headAccountDto!=null){
            responseResult.success();
            responseResult.setData(headAccountDto);
        }else{
            responseResult.error();
        }

        return responseResult;
    }

    /**
     * 传入用户id查询用户头像和昵称以及评论
     * @return
     */
    @RequestMapping("/getcomment")
    @ResponseBody
    public ResponseResult getcomment(int id){
        //用户id
        System.out.println(id);
        ResponseResult responseResult = new ResponseResult();
        HeadAccountDto headAccountDto = userService.getDetail(id);
        if(headAccountDto!=null){
            responseResult.success();
            responseResult.setData(headAccountDto);
        }else{
            responseResult.error();
        }

        return responseResult;
    }

    /**
     * 平台同意商家注册
     * @param id
     * @return
     */
    @RequestMapping("/agreeApply")
    public ResponseResult agreeApply(int id){
        ResponseResult<List<User>> responseResult = new ResponseResult<>();
        responseResult.setStatusCode(200);
        responseResult.setState(StateEnum.SUCCESS);
        responseResult.setData(userService.agreeApply(id));
        return responseResult;
    }

    //通过用户主id去用户角色中间表查询用户及其对应角色
    @RequestMapping("/findUserRoleMenusById")
    public UserRoleMenusDto findUserRoleMenusById() {
        //根据登录获取
        int id = (int) request.getSession().getAttribute("id");
        return userService.findUserRoleMenusById(id);
    }

    @RequestMapping("/changeImage")
    @ResponseBody
    public ResponseResult changeImage(String img){
        System.out.println("111");
        //用户id=5
        int id = (int) request.getSession().getAttribute("id");
        ResponseResult responseResult = new ResponseResult();
        if(userService.changeImage(img,id)){
            responseResult.success();
            responseResult.setMessage("头像修改成功");
        }else {
            responseResult.error();
            responseResult.setMessage("头像修改失败");
        }
        return responseResult;
    }


    /**
     * 输入原密码修改密码
     * @param oldpwd
     * @param newpwd
     * @return
     */
    @RequestMapping("/updatebypwd")
    @ResponseBody
    public ResponseResult updatebypwd(String oldpwd,String newpwd){
        //System.out.println("oldpwd::"+oldpwd+"   new::pwd"+newpwd);
        //用户id
        int id = (int) request.getSession().getAttribute("id");
        ResponseResult responseResult = new ResponseResult();
        if(userService.updateByPwd(id,oldpwd,newpwd)){
            //修改成功
            responseResult.success();
            responseResult.setMessage("密码修改成功");
        }else {
            responseResult.error();
            responseResult.setMessage("密码修改失败，请重试");
        }
        return  responseResult;
    }

    /**
     * 查询用户发表的动态
     * @return
     */
    @RequestMapping("/selectUserPublishRecent")
    @ResponseBody
    public ResponseResult<RecentDto>  selectPublishRecent(){
        int id = (int)request.getSession().getAttribute("id");
        System.out.println("用户id="+id);
        //recentServiceImpl.selectPublishRecent(id);
        UserRecentsDto userRecentsDto = userService.selectPublishRecent(id);
        System.out.println(userRecentsDto.toString());
        ResponseResult responseResult = new ResponseResult();
        if(userRecentsDto!=null){
            List<RecentAndCommentDto> recentAndCommentDtos=userRecentsDto.getRecentAndCommentDtos();
            for (RecentAndCommentDto r:recentAndCommentDtos) {
                //查询点赞数量
                r.setAggreenum(recentCommentService.findAggreeNum(r.getId()));
                //查询评论数量
                r.setCommentnum(recentCommentService.findCommentNum(r.getId()));
            }
            responseResult.success();
            responseResult.setData(userRecentsDto);
        }else{
            responseResult.error();
            responseResult.setMessage("暂无动态");
        }
        return responseResult;
    }
}

